package business.global.pk.tdk;

import java.util.*;
import java.util.stream.Collectors;

import business.global.club.ClubMgr;
import business.global.room.base.AbsBaseRoom;
import business.global.room.base.AbsRoomPos;
import business.global.room.base.AbsRoomPosMgr;
import business.global.shareclub.ShareClubMemberMgr;
import com.ddm.server.common.utils.CommMath;
import com.ddm.server.common.utils.CommTime;
import com.ddm.server.common.utils.TypeUtils;
import core.db.entity.clarkGame.ClubMemberXiFen;
import core.dispatch.DispatcherComponent;
import core.dispatch.event.room.RoomPromotionShare;
import core.dispatch.event.room.RoomXiFenShare;
import jsproto.c2s.cclass.BaseSendMsg;
import jsproto.c2s.cclass.Player;
import jsproto.c2s.cclass.club.ClubRoomPosInfoZhongZhi;
import jsproto.c2s.cclass.pos.RoomPlayerPos;
import jsproto.c2s.cclass.room.BaseCreateRoom;
import jsproto.c2s.iclass.room.SRoom_SportsPointChange;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;

public class TDKRoomPosMgr extends AbsRoomPosMgr {

    @SuppressWarnings({"rawtypes", "unchecked"})
    public TDKRoomPosMgr(TDKRoom room) {
        super(room);
    }

    @Override
    protected void initPosList() {
        // 初始化房间位置
        for (int posID = 0; posID < super.getPlayerNum(); posID++) {
            this.getAllPosList().add(new TDKRoomPos(posID, room));
        }
        //YSJVB
        for (int posID = visitIndex; posID < visitIndex + getVisitListSize(); posID++) {
            this.getAllPosList().add(new TDKRoomPos(posID, true, room));
        }
    }

    /**
     * 是否所有玩家准备
     *
     * @return
     */
    @Override
    public boolean isAllReady() {
        if (null == this.getPosList() || this.getPosList().size() <= 1) {
            // 玩家信息列表没数据
            return false;
        }
        /*
        if (room.getPlayerNum() < 6) {
            return this.getPosList().stream().allMatch(k -> k.getPid() > 0L && k.isReady());
        }
        */
        long readyCount=this.getPosList().stream().filter(k->k.getPid() > 0L && k.isReady()).count();
        long sitCount=this.getPosList().stream().filter(k->k.getPid() > 0L).count();
        return readyCount==sitCount && readyCount>=2;
    }

    /**
     * 随机位置
     *
     * @return
     */
    public int randomPos() {
        List<Integer> posIdList = new ArrayList<>();
        for (int i = 0; i < this.getPlayerNum(); i++) {
            AbsRoomPos pos = getPosList().get(i);
            if (Objects.nonNull(pos) && pos.getPid() > 0L) {
                if (pos.isReady()) {
                    posIdList.add(pos.getPosID());
                }
            }
        }
        if (posIdList.size() <= 0) {
            return 0;
        }
        return posIdList.get(CommMath.randomInt(posIdList.size() - 1));
    }


    /**
     * 通知所有人房间竞技点更新
     */
    @Override
    public boolean notify2RoomSportsPointChange(long pid,long memberId, double value) {
        if (CollectionUtils.isEmpty(this.getPosList())) {
            // 玩家信息列表没数据
            return false;
        }
        AbsRoomPos roomPos = this.getAllPosByPid(pid);
        if (Objects.isNull(roomPos)) {
            return false;
        }
        if(memberId > 0L && memberId == roomPos.memberId()) {
            roomPos.setRoomSportsPoint(CommMath.addDouble(roomPos.getRoomSportsPointValue(), value));
            if(value>0){
                roomPos.setOtherSportsPointConsume(CommMath.subDouble(roomPos.getOtherSportsPointConsume(), value));
            }else if (value<0){
                roomPos.setOtherSportsPointConsume(CommMath.addDouble(roomPos.getOtherSportsPointConsume(), value));
            }
            BaseSendMsg msg = SRoom_SportsPointChange.make(this.room.getRoomID(), roomPos.getPosID(), pid, value);

            if(this.room.getCurSet()!=null){
                //添加到回放记录
                ((TDKRoomSet)this.room.getCurSet()).getRoomPlayBack().addPlaybackList(msg,null);
            }

            this.getAllPosList().forEach(key -> {
                if (Objects.nonNull(key) && !key.isRobot() && key.getPid() > 0L) {
                    key.getPlayer().pushProto(msg);
                }
            });
            return true;
        }
        return false;
    }

    /**
     * 通过PosID获取玩家信息
     *
     * @param posID 玩家位置ID
     * @return
     */
    @Override
    public AbsRoomPos getPosByPosID(int posID) {
        if (CollectionUtils.isEmpty(this.getAllPosList())) {
            // 玩家信息列表没数据
            return null;
        }
        return this.getPosList().stream().filter((x) -> x.getPosID() == posID).findAny().orElse(null);
    }

    /**
     * 是否所有玩家继续下一局
     *
     * @return
     */
    @Override
    public boolean isAllContinue() {
        if (null == this.getPosList() || this.getFullPosCount() <= 1) {
            // 玩家信息列表没数据
            return false;
        }
        // 当局结算时间
        int setEndTime = getRoom().getCurSet().getCurSetEndTime();
        //超时继续，萍乡,继续游戏时间
        this.getPosList().stream().forEach(k -> {
            //YSJVB 间隔，每把游戏间隔，延时
            if (k.getPid() > 0 && !k.isGameReady() && k.getTimeSec() > 0 ? CommTime.nowSecond()- k.getTimeSec() >= 2.6 : setEndTime > 0 && CommTime.nowSecond()- setEndTime >= 2.6) {
                getRoom().continueGame(k.getPid());
            }
        });
        // 玩家在游戏中并且没有准备。
        return this.getPosList().stream().filter(k->k.getPid() > 0L).allMatch(k -> k.getPid() > 0L && k.isGameReady());
    }

    public AbsRoomPos getAllPosByPid(long pid) {
        if (CollectionUtils.isEmpty(this.getPosList())) {
            // 玩家信息列表没数据
            return null;
        }
        return this.getAllPosList().stream().filter((x) -> x.getPid() == pid).findAny().orElse(null);
    }


    //YSJVB  喜分计算
    public void calcXiFen(double xiFen, BaseCreateRoom baseCreateRoom, String dateTime, String dataJsonCfg, int consumeValue, int setCount, int gameId) {
        if (xiFen <= 0D) {
            // 没得喜分
            return;
        }
        Optional<AbsRoomPos> optional=this.getAllPosList().stream().filter(k -> Objects.nonNull(k) && Objects.nonNull(k.getClubMemberBO())&&isPlaying(k)).findFirst();
        if(!optional.isPresent()){
            //没找到玩家
            return;
        }
        // 类型ID
        long unionId = this.getRoom().getSpecialRoomId();
        // 房间名称
        String roomName= baseCreateRoom.getRoomName().isEmpty()?this.getRoom().getGameName():baseCreateRoom.getRoomName();
        // 配置Id
        long configId = baseCreateRoom.getGameIndex();
        // 房间key
        int roomKey = TypeUtils.StringTypeInt(this.getRoom().getRoomKey());

        long clubId=optional.get().getClubID();
        DispatcherComponent.getInstance().publish(new RoomXiFenShare(xiFen,unionId,clubId,roomName,roomKey,configId,getRoom().getRoomID(),getRoom().getBaseRoomConfigure().getGameType().getId(), getRoom().getCityId(),dateTime,dataJsonCfg,setCount,gameId));
    }

}
